package app.ui.adapter;

import app.game.ChessBoard;
import app.game.enums.Chess;
import app.ui.Config;
import app.ui.MainFrame;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.BreakIterator;

/**
 * @Description 处理鼠标事件,落子
 * @Date 2022/4/10 17:11
 * @Created by LYP
 */
public class PutChessAdapter extends MouseAdapter implements Config {

    MainFrame mainFrame;

    public PutChessAdapter(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (!mainFrame.isGameStart) {
            JOptionPane.showMessageDialog(mainFrame, "游戏尚未开始！");
            return;
        } else if (mainFrame.isP2C && mainFrame.getChessBoard().getNowChess() == mainFrame.comChess) {
            JOptionPane.showMessageDialog(mainFrame, "电脑思考中，不能落子！");
            return;
        }
        if (putChess(e.getX(), e.getY(), mainFrame.getChessBoard().getNowChess())) {
            mainFrame.handleEnd();
        }

        if (mainFrame.isP2C && mainFrame.comChess == mainFrame.getChessBoard().getNowChess()) {
            if (mainFrame.getChessBoard().comPutChess(mainFrame.comChess)){
                mainFrame.handleEnd();
            }
        }

    }

    private boolean putChess(int inputX, int inputY, Chess nowChess) {
        ChessBoard chessBoard = mainFrame.getChessBoard();
        if (inputX > ChessBoard.BOARD_LEFT
                && inputX < ChessBoard.BOARD_RIGHT
                && inputY > ChessBoard.BOARD_UP
                && inputY < ChessBoard.BOARD_DOWN) {
            int x = (inputY - ChessBoard.BOARD_UP) / CHESS_SIZE;
            int y = (inputX - ChessBoard.BOARD_LEFT) / CHESS_SIZE;
            if (chessBoard.getChess(x, y) == Chess.EMPTY) {
                chessBoard.setChess(x, y, nowChess);
                chessBoard.drawChessBoard();
                if (chessBoard.isEnd(x, y)) {
                    return true;
                }
                chessBoard.changeNowChess();
            } else {
                JOptionPane.showMessageDialog(mainFrame, "落子失败，此处已有棋子！");
            }
        } else {
            JOptionPane.showMessageDialog(mainFrame, "落子失败，超出棋盘！");
        }
        return false;
    }
}
